import type { NavigationGuardNext, RouteLocationNormalized, Router } from 'vue-router';

import { useAsyncRouteStore } from '@/stores/async-routes';
import { useAuthenticationStore } from '@/stores/auth';

import CommonPage from '../common-page';
import CommonPageName from '../common-page-name';

export default (router: Router) => {
  router.beforeEach((to: RouteLocationNormalized, _, next: NavigationGuardNext) => {
    const authStore = useAuthenticationStore();
    const asyncRouteStore = useAsyncRouteStore();

    if (!authStore.isLogin || asyncRouteStore.isFetched) {
      next();
      return;
    }
    asyncRouteStore
      .fetchUserMenuListAction()
      .then(() => {
        try {
          if (asyncRouteStore.routes.length) {
            asyncRouteStore.addRouteRemover(
              router.addRoute({
                name: CommonPageName.INDEX,
                path: CommonPage.INDEX,
                redirect: {
                  name: asyncRouteStore.routes[0].name,
                },
              }),
            );
            for (const route of asyncRouteStore.routes) {
              asyncRouteStore.addRouteRemover(router.addRoute(route));
            }
          }
        } catch (e) {
          console.log('error: ', e);
          return;
        }
        if (to.name === CommonPageName.NOT_FOUND) {
          next({
            path: CommonPage.NOT_FOUND,
            replace: false,
          });
        }
        next({
          ...to,
          replace: true,
        });
      })
      .catch(() => next(false));
  });
};
